package ldh.im.fxbase.service;

import ldh.im.dto.business.item.LabelInfoItem;
import ldh.im.fxbase.dao.ImCollectDao;
import ldh.im.fxbase.dao.ImLabelDao;
import ldh.im.fxbase.data.pojo.ImCollect;
import ldh.im.fxbase.data.pojo.ImLabel;
import ldh.im.fxbase.data.pojo.status.ImLabelStatus;
import ldh.im.fxbase.util.BeanFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LabelService {

    private ImLabelDao labelDao = BeanFactory.getInstance().getBean(ImLabelDao.class);

    public void updateOrInsert(String userId, List<LabelInfoItem> labelInfoItems) throws SQLException {
        if (labelInfoItems.size() < 1) return;

        List<ImLabel> imLabelList = labelInfoItems.stream().map(cinfo->toLabel(userId, cinfo)).collect(Collectors.toList());

        List<ImLabel> insertImLabelList = new ArrayList<>();
        List<ImLabel> updateImLabelList = new ArrayList<>();

        for(ImLabel imLabel : imLabelList) {
            ImLabel dbLabel = labelDao.getByName(imLabel.getCurrentUserId(), imLabel.getName());
            if (dbLabel == null) {
                insertImLabelList.add(imLabel);
            } else {
                imLabel.setId(dbLabel.getId());
                updateImLabelList.add(imLabel);
            }
        }
        if (insertImLabelList.size() > 0) {
            labelDao.batchInserts(insertImLabelList);
        }
        if (updateImLabelList.size() > 0) {
            labelDao.batchUpdate(updateImLabelList);
        }
    }

    private ImLabel toLabel(String userId, LabelInfoItem cinfo) {
        ImLabel label = new ImLabel();
        label.setName(cinfo.getName());
        label.setServerId(cinfo.getServerId());
        label.setCurrentUserId(userId);
        label.setStatus(ImLabelStatus.wrap(cinfo.getStatus()));
        return label;
    }
}
